from tornado import gen
from base.BaseHandler import AuthHandler
from base.Models import CompanyData


class CompanyDataHandler(AuthHandler):
    @gen.coroutine
    def get(self):
        result = self.result()
        try:
            data = self.get_params()
            company_id = int(data.get("company_id", 0))
            page = int(data.get("page", 1))
            limit = int(data.get("limit", 10))
            key_word = data.get("key_word")
            data_list = []

            company_objects = self.session.query(CompanyData)\
                                  .filter_by(user_id=self.user_id, company_id=company_id, is_delete=0)
            if key_word:
                company_objects = company_objects.filter(CompanyData.remark.like(f"%{key_word}%"))
            company_data = company_objects.order_by(CompanyData.create_time.desc())\
                                          .limit(limit).offset((page - 1) * limit).all()
            for raw in company_data:
                arr = {
                    "id": raw.id,
                    "username": raw.username,
                    "password": raw.password,
                    "remark": raw.remark,
                    "create_time": str(raw.create_time)
                }
                data_list.append(arr)

            data = {
                "data_count": company_objects.count(),
                "data_list": data_list
            }
            result["status"] = 1
            result["msg"] = "数据获取成功！"
            result["data"] = data
        except Exception as e:
            self.logger.error(e)
            result = self.check_except_zh(e)
        self.write(result)

    @gen.coroutine
    def post(self):
        result = self.result()
        try:
            data = self.get_body()
            company_id = self.data_not_null(data, "company_id", "请选择公司！")
            username = self.data_not_null(data, "username", "请输入账户名！")
            password = self.data_not_null(data, "password", "请输入密码！")
            remark = data.get("remark")

            new_data = CompanyData(user_id=self.user_id, company_id=company_id, username=username,
                                   password=password, remark=remark)
            self.session.add(new_data)
            self.record_user_operation(self.user_id, self.user_name, todo=f"新增公司数据-{remark}")
            self.session.commit()
            result["status"] = 1
            result["msg"] = "新增成功！"
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e)
        self.write(result)

    @gen.coroutine
    def put(self):
        result = self.result()
        try:
            data = self.get_body()
            data_id = self.data_not_null(data, "data_id", "请选择要更新的账户！")
            username = self.data_not_null(data, "username", "请输入账户名！")
            password = self.data_not_null(data, "password", "请输入密码！")
            remark = data.get("remark")

            data_verify = self.session.query(CompanyData)\
                              .filter_by(id=int(data_id), user_id=self.user_id, is_delete=0).first()
            if not data_verify:
                self.data_except("请确认账户是否存在！")

            if data_verify.username != username:
                old_name = data_verify.username
                data_verify.username = username
                self.record_user_operation(self.user_id, self.user_name, todo=f"更新账户信息-{old_name}-账户名变更为[{username}]-{data_id}")
            if data_verify.password != password:
                data_verify.password = password
                self.record_user_operation(self.user_id, self.user_name, todo=f"更新账户密码-[{data_verify.username}]-{data_id}")
            data_verify.remark = remark
            self.session.commit()
            result["status"] = 1
            result["msg"] = "更新账户信息成功！"
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e)
        self.write(result)

    @gen.coroutine
    def delete(self):
        result = self.result()
        try:
            data = self.get_body()
            data_id = self.data_not_null(data, "data_id", "请选择要删除的账户！")

            data_verify = self.session.query(CompanyData)\
                              .filter_by(id=int(data_id), user_id=self.user_id, is_delete=0).first()
            if not data_verify:
                self.data_except("请确认账户是否存在！")
            data_verify.is_delete = 1
            self.record_user_operation(self.user_id, self.user_name, todo=f"删除账户信息-{data_verify.username}-{data_id}")
            self.session.commit()
            result["status"] = 1
            result["msg"] = "删除账户信息成功！"
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e)
        self.write(result)

